<template>
  <div class="container">
    <!-- 添加部门组件 -->
    <el-dialog :title="showTitle" :visible="showDialog" @close="btnCancel">
      <!-- 弹层内容 -->
      <el-form
        ref="deptForm"
        label-width="120px"
        :model="formData"
        :rules="rules"
      >
        <el-form-item prop="name" label="部门名称">
          <el-input
            v-model="formData.name"
            style="width: 80%"
            placeholder="1-50个字符"
          />
        </el-form-item>
        <el-form-item prop="code" label="部门编码">
          <el-input
            v-model="formData.code"
            style="width: 80%"
            placeholder="1-50个字符"
          />
        </el-form-item>
        <el-form-item prop="manager" label="部门负责人">
          <el-select
            v-model="formData.manager"
            style="width: 80%"
            placeholder="请选择负责人"
            @focus="getEmployeeSimple"
          >
            <el-option
              v-for="item in peoples"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="introduce" label="部门介绍">
          <el-input
            type="textarea"
            :rows="5"
            style="width: 80%"
            placeholder="1-300个字符"
            v-model="formData.introduce"
            resize="none"
          />
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <el-row type="flex" justify="center" slot="footer">
        <el-col :span="6">
          <el-button style="margin-right: 20px" @click="btnCancel"
            >取消</el-button
          >
          <el-button type="primary" @click="btnOk">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartments,
  addDepartments,
  getDepartDetail,
  updateDepartments,
} from "@/api/departments";
import { getEmployeeSimple } from "@/api/employees";
export default {
  name: "My-AddDept",
  computed: {
    showTitle() {
      return this.formData.id ? "编辑部门" : "新增部门";
    },
  },
  props: {
    // 弹层控件
    showDialog: {
      type: Boolean,
      default: false,
    },
    // 当前操作的节点
    treeNode: {
      type: Object,
      default: null,
    },
  },
  data() {
    // 部门名称的验证规则
    const checkNameRepeat = async (rule, value, callback) => {
      // 先要获取最新的组织架构数据
      const { depts } = await getDepartments();
      let isRepeat = false;
      if (this.formData.id) {
        // 编辑
        // 找到当前部门所有的同级部门
        isRepeat = depts
          .filter(
            (item) =>
              item.pid === this.formData.pid && item.id !== this.formData.id
          )
          .some((item) => item.name === value);
      } else {
        // 新增
        // depts是所有的部门数据
        isRepeat = depts
          .filter((item) => item.pid === this.treeNode.id)
          .some((item) => item.name === value);
      }
      isRepeat ? callback(new Error(`${value}部门已存在`)) : callback();
    };
    // 部门编码验证规则
    const checkCodeRepeat = async (rule, value, callback) => {
      const { depts } = await getDepartments();
      let isRepeat = false;

      if (this.formData.id) {
        //编辑
        isRepeat = depts
          .filter((item) => item.id !== this.formData.id)
          .some((item) => item.code === value);
      } else {
        //新增
        isRepeat = depts.some((item) => item.code === value);
      }

      isRepeat ? callback(new Error(`${value}编码已存在`)) : callback();
    };
    return {
      // 表单数据
      formData: {
        name: "", // 部门名称
        code: "", // 部门编码
        manager: "", // 部门管理者
        introduce: "", // 部门介绍
      },
      rules: {
        // 部门名称
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "部门名称应长度为1-50字符",
            trigger: "blur",
          },
          {
            // 同级部门不能出现重复的部门名称
            trigger: "blur",
            validator: checkNameRepeat,
          },
        ],
        // 部门编码
        code: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "部门编码长度应为1-50字符",
            trigger: "blur",
          },
          {
            // 不能出现重复的部门编码
            trigger: "blur",
            validator: checkCodeRepeat,
          },
        ],
        // 部门管理者
        manager: [
          { required: true, message: "部门负责人不能为空", trigger: "blur" },
        ],
        // 部门介绍
        introduce: [
          { required: true, message: "部门介绍不能为空", trigger: "blur" },
          {
            min: 1,
            max: 300,
            message: "部门介绍长度应为1-300字符",
            trigger: "blur",
          },
        ],
      },
      // 负责人数据
      peoples: [],
    };
  },
  methods: {
    // 获取负责人下拉菜单
    async getEmployeeSimple() {
      this.peoples = await getEmployeeSimple();
    },
    // 点击确定
    btnOk() {
      this.$refs.deptForm
        .validate()
        .then(() => {
          // 验证表单成功
          return this.formData.id
            ? updateDepartments(this.formData)
            : addDepartments({ ...this.formData, pid: this.treeNode.id });
        })
        .then(() => {
          // 新增成功,获取新的数据
          this.$emit("addDepts");
          // 监听事件，关闭弹窗
          this.$emit("update:showDialog", false);
        });
    },
    // 点击取消
    btnCancel() {
      this.formData = {
        name: "", // 部门名称
        code: "", // 部门编码
        manager: "", // 部门管理者
        introduce: "", // 部门介绍
      };
      // 关闭弹窗
      this.$emit("update:showDialog", false);
      // 清空数据和重置校验
      this.$refs.deptForm.resetFields();
    },
    // 获取编辑部门的详情
    async getDepartDetail(id) {
      this.formData = await getDepartDetail(id);
    },
  },
};
</script>

<style scoped lang='less'></style>